﻿using System;
using System.Linq;
using System.Linq.Expressions;

namespace Idsrv4.Admin.EntityFramework.Extensions.Extensions;

public static class QueryableExtensions
{
    public static IQueryable<T> WhereIf<T>(this IQueryable<T> query, bool condition,
        Expression<Func<T, bool>> predicate) => condition
        ? query.Where(predicate)
        : query;

    public static IQueryable<T> TakeIf<T, TKey>(this IQueryable<T> query, Expression<Func<T, TKey>> orderBy,
        bool condition, int limit, bool orderByDescending = true)
    {
        // It is necessary sort items before it
        query = orderByDescending ? query.OrderByDescending(orderBy) : query.OrderBy(orderBy);

        return condition
            ? query.Take(limit)
            : query;
    }

    public static IQueryable<T> PageBy<T, TKey>(this IQueryable<T> query, Expression<Func<T, TKey>> orderBy, int page,
        int pageSize, bool orderByDescending = true)
    {
        const int defaultPageNumber = 1;

        if (query == null) throw new ArgumentNullException(nameof(query));

        // Check if the page number is greater then zero - otherwise use default page number
        if (page <= 0) page = defaultPageNumber;

        // It is necessary sort items before it
        query = orderByDescending ? query.OrderByDescending(orderBy) : query.OrderBy(orderBy);

        return query.Skip((page - 1) * pageSize).Take(pageSize);
    }
}